package objects

import (
	"fmt"
	"io"
	"net/http"
)

type PutStream struct {
	write *io.PipeWriter
	c     chan error
}

func NewPutStream(server, object string) *PutStream {
	pipe, writer := io.Pipe()
	c := make(chan error)
	go func() {
		request, _ := http.NewRequest(http.MethodPut, "http://"+server+"/objects/"+object, pipe)
		client := http.Client{}
		do, err := client.Do(request)
		if err != nil && do.StatusCode != http.StatusOK {
			err = fmt.Errorf("dataServer return http code %d ", do.StatusCode)
		}
		c <- err

	}()
	return &PutStream{write: writer, c: c}
}
func (w *PutStream) Write(p []byte) (n int, err error) {
	return w.write.Write(p)
}
func (w *PutStream) Close() error {
	w.write.Close()
	return <-w.c
}
